using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System;
using System.Threading.Tasks;

namespace CodRevit.ViewModels
{
    /// <summary>
    /// 导出族库视图模型
    /// 负责处理族库导出的业务逻辑
    /// </summary>
    public partial class ExportFamilyViewModel : ObservableObject
    {
        // Revit文档相关字段
        private readonly UIDocument _uiDoc;
        private readonly Document _doc;

        // 用户选择的导出路径
        [ObservableProperty]
        private string _selectedPath = string.Empty;

        // 导出状态信息
        [ObservableProperty]
        private string _exportStatus = "准备导出";

        // 是否正在导出的标志
        [ObservableProperty]
        private bool _isExporting;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="uiDoc">Revit的UIDocument对象</param>
        public ExportFamilyViewModel(UIDocument uiDoc)
        {
            _uiDoc = uiDoc;
            _doc = uiDoc.Document;
        }

        /// <summary>
        /// 浏览文件夹命令
        /// 打开文件夹选择对话框让用户选择导出位置
        /// </summary>
        [RelayCommand]
        private void BrowseFolder()
        {
            using var dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                SelectedPath = dialog.SelectedPath;
            }
        }

        /// <summary>
        /// 导出族库命令
        /// 将当前文档中的所有可编辑族按类别导出到指定文件夹
        /// </summary>
        [RelayCommand]
        private async Task ExportFamiliesAsync()
        {
            // 验证是否选择了导出路径
            if (string.IsNullOrEmpty(SelectedPath))
            {
                ExportStatus = "请先选择导出文件夹!";
                return;
            }

            IsExporting = true;
            ExportStatus = "正在导出族库...";

            try
            {
                // 获取所有可编辑的族
                var collector = new FilteredElementCollector(_doc)
                    .OfClass(typeof(Family));

                // 过滤并按类别分组
                var families = collector
                    .Cast<Family>()
                    .Where(f => f.IsEditable && !f.IsInPlace)
                    .GroupBy(f => f.FamilyCategory?.Name ?? "Uncategorized");

                // 遍历每个类别
                foreach (var categoryGroup in families)
                {
                    // 创建类别文件夹
                    string categoryPath = Path.Combine(SelectedPath, categoryGroup.Key);
                    Directory.CreateDirectory(categoryPath);

                    // 遍历类别中的每个族
                    foreach (var family in categoryGroup)
                    {
                        try
                        {
                            // 生成族文件路径
                            string familyPath = Path.Combine(categoryPath, family.Name + ".rfa");

                            // 处理文件名重复的情况
                            int counter = 1;
                            while (File.Exists(familyPath))
                            {
                                familyPath = Path.Combine(categoryPath,
                                    $"{family.Name}_{counter}.rfa");
                                counter++;
                            }

                            // 创建族文档
                            Document familyDoc = _doc.EditFamily(family);
                            if (familyDoc != null)
                            {
                                try
                                {
                                    // 检查文档是否只读
                                    if (familyDoc.IsReadOnly)
                                    {
                                        ExportStatus = $"跳过只读族: {family.Name}";
                                        await Task.Delay(500);
                                        continue;
                                    }

                                    // 使用SaveAs方法保存族文件
                                    SaveAsOptions options = new SaveAsOptions();
                                    options.OverwriteExistingFile = true;
                                    options.Compact = true; // 压缩文件

                                    // 直接使用SaveAs保存到指定路径
                                    familyDoc.SaveAs(familyPath, options);
                                }
                                catch (Exception saveEx)
                                {
                                    // 如果SaveAs失败，尝试其他方法
                                    ExportStatus = $"保存失败，尝试其他方法: {family.Name}";
                                    await Task.Delay(500);
                                    
                                    try
                                    {
                                        // 尝试先保存到临时位置，然后复制
                                        string tempPath = Path.GetTempFileName() + ".rfa";
                                        familyDoc.SaveAs(tempPath);
                                        
                                        // 复制文件到目标位置
                                        if (File.Exists(familyPath))
                                        {
                                            File.Delete(familyPath);
                                        }
                                        File.Copy(tempPath, familyPath);
                                        File.Delete(tempPath);
                                    }
                                    catch
                                    {
                                        throw saveEx; // 重新抛出原始异常
                                    }
                                }
                                finally
                                {
                                    // 确保关闭族文档
                                    familyDoc.Close(false);
                                }
                            }

                            // 更新导出状态
                            ExportStatus = $"已导出: {family.Name}";
                            await Task.Delay(100); // 短暂延迟以更新UI
                        }
                        catch (Exception ex)
                        {
                            // 处理单个族导出失败的情况
                            ExportStatus = $"导出失败 {family.Name}: {ex.Message}";
                            await Task.Delay(1000); // 延长显示错误信息的时间
                        }
                    }
                }

                ExportStatus = "导出完成!";
            }
            catch (Exception ex)
            {
                // 处理整体导出过程失败的情况
                ExportStatus = $"导出失败: {ex.Message}";
            }
            finally
            {
                IsExporting = false;
            }
        }
    }
}